/*
 * Class: AbstractItem
 * 
 * Created on Sep 26, 2013
 * 
 * (c) Copyright by Minh Tran
 * Global Cybersoft VN.
 * Floor 3-4-5, Helios Building, Quang Trung Software City
 */
package com.minh.tran.sg.model;

import org.jsoup.Jsoup;

import com.minh.tran.sg.Configuration;
import com.minh.tran.sg.Constant;

/**
 * The Class AbstractItem.
 */
public abstract class AbstractItem implements ISItem
{

    /** The _info. */
    protected String _info;

    /**
     * Instantiates a new abstract item.
     *
     * @param info the info
     */
    public AbstractItem(final String info)
    {
        this._info = info;
    }

    /**
     * {@inheritDoc}
     * 
     * @see com.minh.tran.sg.model.ISItem#getId()
     */
    @Override
    public String getId()
    {
        if (this._info == null)
        {
            return null;
        }
        int endPoint = this._info.lastIndexOf(Constant.CHAR_DOT);
        int i = endPoint - 1;
        while (i > 0 && Constant.CHAR_DOT != this._info.charAt(i))
        {
            i--;
        }
        return this._info.substring(i + 1, endPoint);
    }

    /**
     * {@inheritDoc}
     * 
     * @see com.minh.tran.sg.model.ISItem#isASong()
     */
    @Override
    public boolean isASong()
    {
        return this._info.matches(Constant.FORMAT_SONG_NCT);
    }

    /**
     * {@inheritDoc}
     * 
     * @see com.minh.tran.sg.model.ISItem#isPlaylist()
     */
    @Override
    public boolean isPlaylist()
    {
        return this._info.matches(Constant.FORMAT_PLAYLIST_NCT);
    }

    /**
     * Gets the info.
     *
     * @return Returns the info.
     */
    @Override
    public String getInfo()
    {
        return this._info;
    }

    /**
     * {@inheritDoc}
     * 
     * @see com.minh.tran.sg.model.ISItem#getDownloadLink(com.minh.tran.sg.Configuration)
     */
    @Override
    public String getDownloadLink(Configuration config)
    {
        try
        {
            String htmlSource = Jsoup.connect(this._info).get().html();
            String file = config.getKeyLinkNCT();
            int first = htmlSource.indexOf(file);
            int end = htmlSource.indexOf("\"", first);
            file = htmlSource.substring(first, end);
            return file;
        }
        catch (Exception e)
        {
            return null;
        }
    }
}
